{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## LSTM (Long Short Term Memory) Networks for predicting Time Series\n",
    "### Author: Sergei Bulaev. ODS Slack: @ser-serege , Fall 2018"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Introduction\n",
    "\n",
    "In order to understand better the meaning of “Time series Forecast”, let’s split the term in two parts:\n",
    "1. Time series is a sequence of observations taken sequentially in time.\n",
    "2. Forecast means making predictions about a future event.\n",
    "\n",
    "Time Series Forecasting has been in use for quite some time in several industries; It is often used in any industry to guide future decisions, for example, in retail forecasting is very important so that the raw material can be procured accordingly. The best known example is the weather forecast, where the future can be predicted based on the pattern in the past and recent changes. These predictions are very important and usually are the first step to solve other problems.\n",
    "\n",
    "Traditional Time Series analysis involves decomposing the data into its components such as trend component, seasonal component and noise.\n",
    "< Techniques such as ARIMA(p,d,q), moving average, auto regression were used to analyze time series. Stateful RNN’s such as LSTM is found to be very effective in Time Series analysis in the recent past.\n",
    "\n",
    "Neural networks are a very comprehensive family of machine learning models and, in recent years, their applications in finance and economics have dramatically increased.\n",
    "\n",
    "##### What is RNN or Recurrent Neural Networks?\n",
    "\n",
    "The idea of Recurrent Neural Networks (RNNs) is to use sequential information. In a traditional neural network, we assume that all inputs are independent. But for many tasks this is not an optimal idea. RNNs are called recurrent because you perform the same task for each element of a sequence, with the output depending on the previous calculations.\n",
    "\n",
    "RNN is a special case of neural network similar to convolutional neural networks, the difference being that RNN’s can retain its state of information.\n",
    "\n",
    "##### What is LSTM?\n",
    "\n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/1.png\" />\n",
    "\n",
    "LSTM is a variant of the RNN architecture. It was difficult to train models using traditional RNN architectures. Recent advancements demonstrate state of the art results using LSTM(Long Short Term Memory). An LSTM cell has 5 essential components which allows it to model both long-term and short-term data: the cell state, hidden state, input gate, forget gate and output gate. One critical advantage of LSTMs is their ability to remember from long-term sequences.\n",
    "The LSTM architecture was able to take care of the vanishing gradient problem in the traditional RNN.\n",
    "\n",
    "\n",
    "\n",
    "The goal of this Tutorial is to provide a practical guide to neural networks for forecasting financial time series data.\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "###### Using LSTM Flexibility to use multiple combinations of parametres:\n",
    "1. Many to a model (useful if you want to predict today, taking into account all previous input),\n",
    "1. Many-to-Many models (useful when predicting multiple future steps at the same time, taking into account all previous inputs)\n",
    "and a number of other deviations from it.\n",
    "2. We can personalize several things, for example - the size of the monitoring window that needs to be predicted in the current phase,\n",
    "3. The number of steps we want to predict in the future\n",
    "4. Put the current prediction back into the window to do the prediction in the next step (this technique is also known as the progress window).\n",
    "5.  To define the best LSTM architecture\n",
    "5. And so on"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LSTM networks were presented in the paper Hochreiter and Schmidhuber, 1997,\n",
    "\n",
    "The first work about LSTM networks was in 1997 by Hochreiter and Schmidhuber to solve the problem of long-term dependencies.\n",
    "\n",
    "All RNNs have the form of a chain of repeating modules.\n",
    "<The LSTM network is a similar chain, but the repeating module has a different structure. Instead of a single layer, it contains four layers that interact in a special way. \n",
    "    \n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/6.png\" />\n",
    "    \n",
    "###### The main technical idea at LSTM networks \n",
    "is that the cell state represented by a horizontal line at the top of the following figure.\n",
    "\n",
    "The state of the cell can be compared to a conveyor belt. It passes through the entire chain, with only minor linear interactions.\n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/8.png\" />\n",
    "\n",
    "\n",
    "The LSTM network has the ability to remove and add information to the cell state. This process is regulated by special structures called gates (gate).\n",
    "###### Gate \n",
    "is a mechanism that allows information to be passed selectively. It consists of a sigmoid layer (activation function-sigmoid) and a point multiplication operation.\n",
    "\n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/9.png\" />\n",
    "\n",
    "The output of the sigmoid layer is a number from 0 to 1, which determines the level of transmission. Zero means\" don't miss anything \"and one means\"skip all\".  The cell has three gates that control its state."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The first gate \"forget gate\"\n",
    "The first gate decide which information to remove from the cell state. This decision is made by sigmoid-layer.\n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/10.png\" />\n",
    "\n",
    "### The second gate \n",
    "The second gate decide which new information to write to the cell state. This stage is divided into two parts. First, the sigmoid layer, called the input gate, decides which values need to be updated. The tanh layer then creates a vector of New CT ' candidate values that can be added to the cell state.\n",
    "<img src=\"http://datareview.info/wp-content/uploads/2015/09/11.png\" />\n",
    "\n",
    "### The third gate\n",
    "\n",
    "The third gate decide what we’re going to output. This output will be based on our cell state, but will be a filtered version. First, we run a sigmoid layer which decides what parts of the cell state we’re going to output. Then, we put the cell state through tanh (to push the values to be between −1 and 1) and multiply it by the output of the sigmoid gate, so that we only output the parts we decided to.\n",
    "<img src=\"http://colah.github.io/posts/2015-08-Understanding-LSTMs/img/LSTM3-focus-o.png\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Let's start to build a model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import sqrt\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import plotly.graph_objs as go\n",
    "import plotly.offline as py\n",
    "import seaborn as sns\n",
    "from keras.layers import LSTM, Activation, Dense, Dropout\n",
    "from keras.models import Sequential\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
    "from sklearn.model_selection import TimeSeriesSplit, cross_val_score\n",
    "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### This tuturial will be based on data about real time-series data of total ads watched by hour in one of our games."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"../../data/ads_hour.csv\", index_col=[\"Date\"], parse_dates=[\"Date\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with plt.style.context(\"bmh\"):\n",
    "    plt.figure(figsize=(15, 8))\n",
    "    plt.title(\"Ads watched (hour ticks)\")\n",
    "    plt.plot(df.ads);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The first step \n",
    "We will try approach with window data. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Making a function to break data, scale data, window data\n",
    "\n",
    "\n",
    "def get_window_data(data, window):\n",
    "    # Get window data and scale\n",
    "    scaler = MinMaxScaler(feature_range=(0, 1))\n",
    "    data = scaler.fit_transform(data.reshape(-1, 1))\n",
    "\n",
    "    X = []\n",
    "    y = []\n",
    "\n",
    "    for i in range(len(data) - window - 1):\n",
    "        X.append(data[i : i + window])\n",
    "        y.append(data[i + window + 1])\n",
    "\n",
    "    X = np.asarray(X)\n",
    "    y = np.asarray(y)\n",
    "    return X, y, scaler\n",
    "\n",
    "\n",
    "window_size = 50\n",
    "X, y, scaler = get_window_data(df.values, window_size)\n",
    "\n",
    "test_split = int(len(df) * 0.8)\n",
    "\n",
    "X_train = X[:test_split]\n",
    "X_test = X[test_split:]\n",
    "\n",
    "y_train = y[:test_split]\n",
    "y_test = y[test_split:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Neural Network structure \n",
    "\n",
    "##### Dense \n",
    "implements the operation: output = activation(dot(input, kernel) + bias) where activation is the element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, and bias is a bias vector created by the layer (only applicable if use_bias is True).\n",
    "\n",
    "##### Dropuout \n",
    "Applies Dropout to the input.\n",
    "Dropout consists in randomly setting a fraction rate of input units to 0 at each update during training time, which helps prevent overfitting.\n",
    "\n",
    "\n",
    "##### Optimizer \n",
    "SGD (Stochastic gradient descent optimizer. ) , RMSprop (It is recommended to leave the parameters of this optimizer at their default values (except the learning rate, which can be freely tuned). Adam\n",
    "\n",
    "Adam, an algorithm for first-order gradient-based optimization of stochastic objective functions, based on adaptive estimates of lower-order mo- ments. The method is straightforward to implement, is computationally efficient, has little memory requirements, is invariant to diagonal rescaling of the gradients, and is well suited for problems that are large in terms of data and/or parameters. The method is also appropriate for non-stationary objectives and problems with very noisy and/or sparse gradients. The hyper-parameters have intuitive interpre- tations and typically require little tuning.\n",
    "\n",
    "##### Metrics \n",
    "A metric is a function that is used to judge the performance of your model. Metric functions are to be supplied in the metrics parameter when a model is compiled.\n",
    "It coud be Custom metrics , binary_accuracy, categorical_accuracy. A metric function is similar to a loss function, except that the results from evaluating a metric are not used when training the model. You may use any of the loss functions as a metric function.\n",
    "\n",
    "\n",
    "##### Loss function\n",
    "MSE, MAPE, MAE, Cosine_proximity, categorical_crossentropy\n",
    "\n",
    "\n",
    "##### Activation \n",
    "Activations can either be used through an Activation layer, or through the activation argument supported by all forward layers.\n",
    "It could be: tanh, softmax, relu , sigmoid, exponential, linear\n",
    "\n",
    "##### Callbacks\n",
    "A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callbacks (as the keyword argument callbacks) to the .fit() method of the Sequential or Model classes. The relevant methods of the callbacks will then be called at each stage of the training.\n",
    "We will use \"history\": callback that records events into a History object. This callback is automatically applied to every Keras model. The History object gets returned by the fit method of models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train.shape, X_test.shape, y_train.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import LSTM, Activation, Dense, Dropout\n",
    "from keras.models import Sequential\n",
    "\n",
    "# ------- Building the LSTM model --------- #\n",
    "\n",
    "model = Sequential()\n",
    "model.add(LSTM(50, input_shape=(window_size, 1)))  # 50neurons, and and window_size = 50\n",
    "model.add(Dropout(0.2))\n",
    "model.add(Dense(1))\n",
    "model.add(Activation(\"linear\"))\n",
    "model.compile(loss=\"mse\", optimizer=\"adam\")\n",
    "\n",
    "# ------- Building the LSTM model --------- #"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can just fit or write it to history of learning. Then we will see the process of learning\n",
    "\n",
    "history = model.fit(\n",
    "    X_train,\n",
    "    y_train,\n",
    "    epochs=20,\n",
    "    batch_size=10,\n",
    "    validation_data=(X_test, y_test),\n",
    "    verbose=2,\n",
    "    shuffle=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mse_lstm = mean_squared_error(\n",
    "    scaler.inverse_transform(y_test), scaler.inverse_transform(model.predict(X_test))\n",
    ")\n",
    "print(\"RMSE for LSTM {:.2f}\".format(np.sqrt(mse_lstm)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# make functions for plotting history and predictions\n",
    "\n",
    "\n",
    "def plot_history(history):\n",
    "    plt.figure(figsize=(6, 4))\n",
    "    plt.plot(history.history[\"loss\"], label=\"Train\")\n",
    "    plt.plot(history.history[\"val_loss\"], label=\"Test\")\n",
    "    plt.title(\"Loss over epoch\")\n",
    "    plt.xlabel(\"Epoch\")\n",
    "    plt.ylabel(\"Loss\")\n",
    "    plt.legend()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def plot(X_test):\n",
    "    pred = model.predict(X_test)\n",
    "    pred_inverse = scaler.inverse_transform(pred.reshape(-1, 1))\n",
    "    y_test_inverse = scaler.inverse_transform(y_test.reshape(-1, 1))\n",
    "\n",
    "    # Calculate mean_squared_error. Previosly we did MinMax scale, so apply inverse_transform to recover values\n",
    "    rmse = sqrt(mean_squared_error(y_test_inverse, pred_inverse))\n",
    "    print(\"Test RMSE: %.3f\" % rmse)\n",
    "    plt.figure(figsize=(15, 8))\n",
    "    plt.plot(pred_inverse, label=\"predict\")\n",
    "    plt.plot(y_test_inverse, label=\"actual\")\n",
    "    plt.legend()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_history(history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot(X_test)\n",
    "plot_history(history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# So, we got not nice predictions. Lets's try to add return sequences, changenumber of neurons,\n",
    "# batch size  and optimizer to rmsprop\n",
    "\n",
    "# ------- Building the LSTM model --------- #\n",
    "\n",
    "model = Sequential()\n",
    "model.add(LSTM(input_dim=1, output_dim=50, return_sequences=True))\n",
    "model.add(Dropout(0.1))\n",
    "model.add(LSTM(64, return_sequences=False))\n",
    "model.add(Dropout(0.2))\n",
    "model.add(Dense(1))\n",
    "model.add(Activation(\"linear\"))\n",
    "model.compile(loss=\"mse\", optimizer=\"rmsprop\")\n",
    "\n",
    "# ------- Building the LSTM model --------- #"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Fitting the model\n",
    "\n",
    "history = model.fit(\n",
    "    X_train, y_train, batch_size=256, nb_epoch=20, validation_data=(X_test, y_test)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_history(history)\n",
    "plot(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Actually not that result that we expect from Neural Network! Keep on trying"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "scaler = MinMaxScaler(feature_range=(-1, 1))\n",
    "scaled = scaler.fit_transform(df.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"../../data/ads_hour.csv\", index_col=[\"Date\"], parse_dates=[\"Date\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Another one approach to break the data using \"shift\"\n",
    "# Take bigger window\n",
    "window_size = 100\n",
    "\n",
    "df_s = df.copy()\n",
    "for i in range(window_size):\n",
    "    df = pd.concat([df, df_s.shift(-(i + 1))], axis=1)\n",
    "df.dropna(axis=0, inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_index = round(0.8 * df.shape[0])\n",
    "\n",
    "X = df.iloc[:test_index, :]\n",
    "y = df.iloc[test_index:, :]\n",
    "\n",
    "# from sklearn.utils import shuffle\n",
    "# train = shuffle(train)\n",
    "\n",
    "X_train = X.iloc[:, :-1]\n",
    "y_train = X.iloc[:, -1]\n",
    "X_test = y.iloc[:, :-1]\n",
    "y_test = y.iloc[:, -1]\n",
    "\n",
    "# train_X = train_X.values\n",
    "# train_y = train_y.values\n",
    "# test_X = test_X.values\n",
    "# test_y = test_y.values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler = MinMaxScaler(feature_range=(-1, 1))\n",
    "X_train = scaler.fit_transform(X_train.values)\n",
    "X_test = scaler.transform(X_test.values)\n",
    "\n",
    "\n",
    "scalere = MinMaxScaler(feature_range=(-1, 1))\n",
    "y_train = scalere.fit_transform(y_train.values.reshape(-1, 1))\n",
    "y_test = scalere.transform(y_test.values.reshape(-1, 1))\n",
    "\n",
    "X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)\n",
    "X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)\n",
    "\n",
    "X_train.shape[0], X_train.shape[1], X_train.shape[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------- Building the LSTM model --------- #\n",
    "\n",
    "model = Sequential()\n",
    "model.add(\n",
    "    LSTM(\n",
    "        input_shape=(X_train.shape[1], X_train.shape[2]),\n",
    "        output_dim=50,\n",
    "        return_sequences=True,\n",
    "    )\n",
    ")\n",
    "model.add(Dropout(0.5))\n",
    "model.add(LSTM(64))\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Dense(1))\n",
    "model.add(Activation(\"linear\"))\n",
    "model.compile(loss=\"mse\", optimizer=\"adam\")\n",
    "\n",
    "# ------- Building the LSTM model --------- #"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Shows the architecture of NN\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = model.fit(\n",
    "    X_train, y_train, batch_size=64, nb_epoch=20, validation_data=(X_test, y_test)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_history(history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yhat_inverse = scalere.inverse_transform(yhat.reshape(-1, 1))\n",
    "y_test_inverse = scalere.inverse_transform(y_test.reshape(-1, 1))\n",
    "\n",
    "rmse = sqrt(mean_squared_error(y_test_inverse, yhat_inverse))\n",
    "print(\"Test RMSE: %.3f\" % rmse)\n",
    "\n",
    "pyplot.plot(yhat_inverse, label=\"predict\")\n",
    "pyplot.plot(y_test_inverse, label=\"actual\")\n",
    "pyplot.legend()\n",
    "pyplot.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### RMSE for LSTM 3707. Is better but not fair enough"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"../../data/ads_hour.csv\", index_col=[\"Date\"], parse_dates=[\"Date\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "X = df[\"ads\"].values.reshape(-1, 1)\n",
    "scaler = MinMaxScaler(feature_range=(0, 1))\n",
    "X = scaler.fit_transform(X)\n",
    "\n",
    "X.shape, df[\"ads\"].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# test_index = round(0.8*df.shape[0])\n",
    "\n",
    "train_size = round(len(X) * 0.7)\n",
    "test_size = len(X) - train_size\n",
    "train, test = X[0:train_size, :], X[train_size : len(X), :]\n",
    "print(len(train), len(test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_dataset(dataset, look_back=360):\n",
    "    X, Y = [], []\n",
    "    for i in range(len(dataset) - look_back):\n",
    "        a = dataset[i : (i + look_back), 0]\n",
    "        X.append(a)\n",
    "        Y.append(dataset[i + look_back, 0])\n",
    "    return np.array(X), np.array(Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "look_back = 5\n",
    "X_train, y_train = create_dataset(train, look_back)\n",
    "X_test, y_test = create_dataset(test, look_back)\n",
    "\n",
    "X_train.shape, y_train.shape, X_test.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Making 3D vector\n",
    "X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))\n",
    "X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))\n",
    "\n",
    "X_train.shape, X_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------- Building the LSTM model --------- #\n",
    "\n",
    "model = Sequential()\n",
    "model.add(LSTM(100, input_shape=(X_train.shape[1], X_train.shape[2])))\n",
    "model.add(Dense(1))\n",
    "model.compile(loss=\"mae\", optimizer=\"adam\")\n",
    "history = model.fit(\n",
    "    X_train,\n",
    "    y_train,\n",
    "    epochs=300,\n",
    "    batch_size=100,\n",
    "    validation_data=(X_test, y_test),\n",
    "    verbose=0,\n",
    "    shuffle=False,\n",
    ")\n",
    "\n",
    "# ------- Building the LSTM model --------- #"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_history(history)\n",
    "plot(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finaly we got good results with RMSE = 2891\n",
    "\n",
    "##### In conclusion,\n",
    "we can say that RNNs are pretty good instrument for predicting time series. It has pros and cons.\n",
    "It could give very good results because LSTM remember previos periods, peaks, trens and other moments. \n",
    "More than 1000 parameters to tune model makes choise of LSTM in simple time prediction hard. You can change numer of layes, choose dropout, window size, optimizer, bathc size, number of epochs, return or not renurn sequences.\n",
    "<It seems, that choose of LSTM is good, when ARIMA, SARIMA, Prophet aren't give acceptable metrics and results. Or when we have lots of additional information to Time series. For example: Using News to Predict Stock Movements, of sales with lots of conditions from business that describe different changes in Time Series."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### References\n",
    "\n",
    "http://datareview.info/article/znakomstvo-s-arhitekturoy-lstm-setey/\n",
    "https://cyberleninka.ru/article/v/prognozirovanie-tendentsii-finansovyh-vremennyh-ryadov-s-pomoschyu-neyronnoy-seti-lstm\n",
    "http://alexsosn.github.io/ml/2015/11/17/LSTM.html\n",
    "https://github.com/rishikksh20/LSTM-Time-Series-Analysis/blob/master/LSTM_Time_Series_Analysis.ipynb\n",
    "https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/\n",
    "https://towardsdatascience.com/using-lstms-to-forecast-time-series-4ab688386b1f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
